<template>
  <div ref="chartRef" style="width: 100%; height: 180px"/>
</template>

<script setup>
import {onMounted, watch} from "vue";
import {useEcharts} from "../../../../hook/ useEcharts";
import * as echarts from "echarts";

const props = defineProps({
      value: {
        type: Object,
        default: () => ({data: [], title: '', color: [['#2DE1FD', '#0E5FFF'], ['#FFA600', '#FEDB65']]}),
      },
    })
;

const {chartRef, initChart, updateChart} = useEcharts();

const option = {
  tooltip: {
    trigger: 'item',
    position: function (point) {
      // 设置 tooltip 显示在鼠标右侧，偏移量为 [10, 0]
      return [point[0] + 10, point[1]];
    }
  },
  legend: {
    orient: 'horizontal',
    bottom: '0%',
    textStyle: {
      color: "#fff"
    },
    itemWidth: 15,
    itemHeight: 10,
  },
  title: {
    text: props.value.title,
    x: 53,
    y: 60,
    textStyle: {
      color: '#fff',
      fontSize: 14,
    },
    textAlign: 'center',
  },
  series: [
    {
      type: 'pie',
      radius: ['55%', '85%'],
      center: ['50%', '40%'],
      avoidLabelOverlap: false,
      itemStyle: {
        normal: {
          color: (params) => {
            return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: props.value.color[params.dataIndex][0] || '#2DE1FD',
              },
              {
                offset: 1,
                color: props.value.color[params.dataIndex][1] || '#0E5FFF',
              },
            ])
          },
          label: {
            show: false,
          },
          labelLine: {
            show: false,
          },
        },
      },
      label: {
        show: false,
        position: 'center'
      },
      labelLine: {
        show: false
      },
      data: props.value.data
    }
  ]
};

watch(() => {
  return props.value
}, (newVal) => {
  updateChart({
    title: {
      text: newVal.title
    },
    series: [{
      itemStyle: {
        normal: {
          color: (params) => {
            return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: newVal.color[params.dataIndex][0] || '#2DE1FD',
              },
              {
                offset: 1,
                color: newVal.color[params.dataIndex][1] || '#0E5FFF',
              },
            ])
          },
        },
      },
      data: newVal.data
    }]
  })
}, {deep: true})

onMounted(() => {
  // 初始化图表
  initChart(option);
});

</script>

<style scoped lang="scss">

</style>
